package com.ly.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ly.bean.Result;
import com.ly.biz.BizException;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;
import java.util.Map;

public class Utils {
    private static ObjectMapper objectMapper = new ObjectMapper();
    public static void writeResult(int code, String msg, Object data, HttpServletResponse response){
        response.setContentType("application/json;charset=utf-8");
        Result result = new Result(code,msg,data);
        try {
            String json = objectMapper.writeValueAsString(result);
            response.getWriter().append(json);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("转换JSON失败!",e);
        } catch (IOException e) {
            throw new RuntimeException("传送JSON失败!",e);
        }
    }

    public static void check(boolean b, String msg) throws BizException {
        if (b) throw new BizException(msg);
    }

    public static void checkEmpty(Object value, String msg) throws BizException {
        if (value == null) throw new BizException(msg);
        if(value instanceof String) {
            check(((String) value).isBlank(), msg);
        }
        if(value instanceof Collection) {
            check(((Collection) value).isEmpty(), msg);
        }
        if(value instanceof Map) {
            check(((Map) value).isEmpty(), msg);
        }
    }
}
